package com.zuorenke.model.dto;

import com.zuorenke.help.MyCollectionUtils;
import com.zuorenke.model.po.Lesson;
import com.zuorenke.model.po.ReportModelTeacher;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Z.R.K
 * @description
 * @create 2019-04-12 17:45:46
 **/
@Component
public class CacheReport {
	private Object lockLesson = new Object();
	private Object lockTeacher = new Object();
	private Map<Long, Lesson> lessonMapping = new HashMap<>();
	private Map<String, ReportModelTeacher> teacherReportMapping = new HashMap<>();
	
	public Lesson getLessonByLessonId(Long lessonId, Function<Long, Lesson> fun){
		Lesson lesson = lessonMapping.get(lessonId);
		if(lesson == null){
			lesson = fun.apply(lessonId);
			synchronized (lockLesson){
				lessonMapping.putIfAbsent(lessonId, lesson);
			}
			lesson = lessonMapping.get(lessonId);
		}
		return lesson;
	}
	
	public void initTeacherReport(List<ReportModelTeacher> reportTeachers){
		teacherReportMapping = reportTeachers.stream().collect(Collectors.toMap(
				item -> item.getReportMonth() + "_" + item.getTeacherId() + "_" + item.getSubjectId()
				, item -> item));
	}
	
	public ReportModelTeacher getTeacherReport(String key){
		synchronized (lockTeacher){
			return teacherReportMapping.computeIfAbsent(key, k -> new ReportModelTeacher());
		}
	}
	
	public List<ReportModelTeacher> getTeacherReports(){
		return teacherReportMapping.values().stream()
				.collect(Collectors.toList());
	}
	
	
	public void destoryLessonMapping(){
		lessonMapping.clear();
		lessonMapping = new HashMap<>();
	}
	
	
	public void destoryTeacherReport(){
		teacherReportMapping.clear();
		teacherReportMapping = new HashMap<>();
	}
	
	public void clearCache(){
		destoryLessonMapping();
		destoryTeacherReport();
	}
	
	ReportModelTeacher getReportModelTeacher(){
		return new ReportModelTeacher();
	}
}
